//
//  MMGNetworkTool.swift
//  MyMicroblog
//
//  Created by Mac on 17/1/5.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

// 声明请求方法枚举
enum HttpMethod: Int {
    case MethodGet = 0
    case MethodPost = 1
}
class MMGNetworkTool: AFHTTPSessionManager {

    // 提供单例对象
    static let shared: MMGNetworkTool = {
    
        let tool = MMGNetworkTool()
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    // 提供封装方法
    func request(Method:HttpMethod, urlString:String, parameters:Any?, finished:@escaping (Any?, Error?) -> ()) {
        
        // 封装回调方法
        // 成功的回调
        let successBack = { (task: URLSessionDataTask, responseObject:Any?) -> () in
        
            finished(responseObject, nil)
        }
        // 失败的回调
        let failureBack = {(task: URLSessionDataTask?, error: Error) -> () in
        
            finished(nil,error)
        }
        
        if Method == .MethodGet {
            
            self.get(urlString, parameters: parameters, progress: nil, success: successBack, failure: failureBack)
        }else{
        
            self.post(urlString, parameters: parameters, progress: nil, success: successBack, failure: failureBack)
        }
    }
}
